package caidan.net;

import jinyilw.tools.net.NetConfig;
import jinyilw.tools.net.ServerTools;
import jinyilw.tools.net.dev.BaseClient;
import jinyilw.tools.net.dev.CommandPacket;
import jinyilw.tools.net.dev.NetworkPacket;
import jinyilw.tools.net.file.FileTransfer;

import java.io.File;

public class AdminNewFoodPanel extends AbstractNewFoodPanel
{
	private static final long serialVersionUID = -8424692830726670977L;
	private ServerTools serverTools;

	public AdminNewFoodPanel(ServerTools tools)
	{
		serverTools = tools;
	}

	public void initNet()
	{
		initFromFile();
		serverTools.startFileTransferServer(NetConfig.fileServerPort,
				localNewFoodFolder, netNewFoodFolder);
		serverTools.addReceiveClientPacketOperator((BaseClient c) ->
		{
			for (NetworkPacket packets : c.getReceivedPackets())
			{
				if (packets instanceof CommandPacket)
				{
					CommandPacket packet = (CommandPacket) packets;
					int command = packet.getCommandID();
					// System.out.println("Command.C:" + command);
					if (command == Command.C.sendNewFoodToNet)
						new Thread(() ->
						{
							addNewFoodFromNet(c, packet);
						}).start();
					else if (command == Command.C.getAllNewFood)
						new Thread(() ->
						{
							sendAllNewFood(c, packet);
						}).start();
					else if (command == Command.C.sendUserInfo)
						c.setInfo(packet);
				}
			}
		});
	}

	public synchronized void sendAllNewFood(BaseClient c, CommandPacket packet)
	{
		for (NewFoodLabel label : newFoodLabels)
			c.sendCommand(label.foodData, Command.S.sendAllNewFoodToClient);
		c.sendCommand(packet, Command.S.endSendAllNewFood);
	}

	public void addNewFoodFromNet(BaseClient c, CommandPacket foodData)
	{
		NewFoodLabel label = new NewFoodLabel(foodData);
		addNewFoodLabel(label);
		File[] files = c.getReceivedFiles();
		label.setFiles(files);
	}

	//	private synchronized NewFoodLabel getLabel(long longData, double doubleData)
	//	{
	//		for (NewFoodLabel label : newFoodLabels)
	//			if (longData == label.foodData.getLongData()
	//					&& doubleData == label.foodData.getDoubleData())
	//				return label;
	//		return null;
	//	}

	public void initFromFile()
	{
		readFromFile();
		for (NewFoodLabel label : newFoodLabels)
			contentPanel.add(label);
		for (NewFoodLabel label : localLabels)
			contentPanel.add(label);
		revalidate();
		repaint();
	}

	@Override
	public boolean isConnected()
	{
		return false;
	}
	@Override
	public boolean isClient()
	{
		return false;
	}
	@Override
	public String getDataFolderPath()
	{
		return "serverData";
	}
	@Override
	public String getNewFoodFolderPath()
	{
		return "serverNewFood";
	}

	@Override
	public FileTransfer getFileTransfer()
	{
		return null;
	}

	@Override
	public boolean sendCommandToNet(CommandPacket data, int command)
	{
		return serverTools.broadcastCommand(data, command);
	}
}
